package com.example.beryl.proSystem;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.beryl.R;
import com.example.beryl.Util.HandlePublic;
import com.example.beryl.Util.ReceiveBroadCast;
import com.example.beryl.entity.Action;
import com.example.beryl.entity.UserData.EQ;
import com.example.beryl.entity.UserData.Person;
import com.example.beryl.http.Net_startWork;
import com.example.beryl.http.Net_userData;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 开工记录
 */

public class startWork extends AppCompatActivity {
    ReceiveBroadCast mBroadcastReceiver = new ReceiveBroadCast();
    public boolean mReceiverTag = false;
    HandlePublic handlePublic = new HandlePublic();
    Net_startWork net_startWork = new Net_startWork();
    JSONArray jsonArray = null;
    JSONArray jsonArray1 = null;
    JSONArray jsonArray2 = null;
    JSONArray jsonArray3 = null;//获取批次号json
    private static final int SW = 1;
    private static final int GP = 2;
    private static final int SS = 3;
    private static final int EQ = 4;
    private static final int EM = 5;
    private static final int GC = 6;
    private static final int SBG = 7;
    private static final int GM = 8;
    private ListView listView;
    boolean isSelect = false;
    private static final List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private SimpleAdapter adapter1;
    ArrayAdapter<String> adapter = null;
    private int ii = 99999;//下拉判断
    private String pro = "";
    private static String BarCode = "";



    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        mReceiverTag = true;
        filter.addAction("com.android.server.scannerservice.broadcast"); //添加过滤条件，接收广播
        registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_work);
        Toolbar toolbar = findViewById(R.id.toolbar);
        ConstraintLayout constraintLayout = findViewById(R.id.cl_main);
        setSupportActionBar(toolbar);
        toolbar.setTitle("开工记录");
        toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back);
        Spinner spinner = findViewById(R.id.sp_dropdown);
        Button button = findViewById(R.id.submit1);
        listView = (ListView) findViewById(R.id.listView);
        toolbar.setNavigationOnClickListener(view -> finish());
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getGroupId()) {
                case 0:
                case 1:
                case 2:
                case 3: {
                    Toast.makeText(startWork.this, "点了一下" + item.getTitle(), Toast.LENGTH_SHORT).show();
                    break;
                }
            }
            return false;
        });

//        if (Action.person != null)
//        {
//            final EditText editText = findViewById(R.id.people);
//            editText.setText(Action.person.cPsn_Name);
//        }

        //下拉框选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                pro = adapter.getItem(i);
                //if (isSelect != false)
                //{
                //if (ii != i)
                //{
                getChance(pro);
                //ii = i;
                //}
                //}
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        //listView获取点击数据
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            //当不是第一行时才弹窗
            if (i != 0) {
                HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(i);
                if (map.containsValue("导针规格") || map.containsValue("化成液") || map.containsValue("分散液") || map.containsValue("单体") ||
                        map.containsValue("氧化剂") || map.containsValue("铝壳") || map.containsValue("胶盖") || map.containsValue("电解液")) {
                    getDialogMessage(i);//传行数

                } else {

                }
                //getDialogMessage(i);//传行数
            }
        });

        EditText editText = findViewById(R.id.people);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 4) {
                    boolean T = handlePublic.isNumericZidai(charSequence.toString());
                    if (T) {
                        String PersonNUm = "EM-" + charSequence.toString();
                        getEMPQ(PersonNUm);
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        Button buttonEQ = findViewById(R.id.EQSelect1);
        buttonEQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Net_userData net_userData = new Net_userData();
                if (!pro.equals("")) {
                    EditText editText1 = findViewById(R.id.EQNum);
                    String input = editText1.getText().toString();
                    if (!input.contains("#")) {
                        input = input + "#";
                    }
                    String finalInput = input;
                    editText1.setText(finalInput);
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("设备", finalInput);
                    hashMap.put("参数", pro);
                    String json = handlePublic.MakeJson(hashMap);
                    System.out.println(json);
                    //handlePublic.startLoad(startWork.this);
                    new Thread(() -> {
                        List<String> list = new ArrayList<>();
                        list = net_userData.User_CommonMethod(Action.action.GetEM, json);
                        handlePublic.setmHandler(EQ, list);
                    }).start();
                } else {
                    handlePublic.Alert("请确认好工序", startWork.this);
                }
            }
        });

        //提交方法
        button.setOnClickListener(view -> {
            EditText editText12 = findViewById(R.id.PC);
            EditText editText1 = findViewById(R.id.people);
            String ed = editText12.getText().toString();
            String ed1 = editText1.getText().toString();
            if (ed.equals("") || ed1.equals("")) {
                handlePublic.Alert("请完善表格!", startWork.this);
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(startWork.this);
                builder.setTitle("提示");
                builder.setMessage("是否提交");
                builder.setPositiveButton("是", (dialogInterface, i) -> {
                    try {
                        checkData();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                });
                builder.setNegativeButton("否",
                        (dialog, which) -> dialog.dismiss());
                if (!isFinishing()) {
                    builder.create().show();
                }
            }
        });

        //手动输入流传单号
        Button button1 = findViewById(R.id.selectButtom1);
        button1.setOnClickListener(view -> {
            EditText editText1 = findViewById(R.id.SQ);
            String LCDnum = editText1.getText().toString();
            if (!LCDnum.equals("")) {
                if (!LCDnum.contains("WO-")) {
                    LCDnum = "WO-" + LCDnum;
                }
                DataResult(LCDnum);
            } else {
                handlePublic.Alert("请输入流传单号!", startWork.this);
            }
        });
        //结果回调函数
        mBroadcastReceiver.setScanHeadListener(this::DataResult);
        //网络回调
        handlePublic.setGetResult((what, t) -> {
            getData(what, t);
        });

        //下拉菜单
        SharedPreferences nw_qq = getSharedPreferences("qq_xml", Context.MODE_PRIVATE);
        String prc =nw_qq.getString("process","");
        if (prc != "")
        {
            setSpinner(prc);
        }else
        {
            handlePublic.Alert("登录状态过期，退出程序重新登陆", startWork.this);
        }

        //更新操作员
        handlePublic.setGetPersonRet(ret -> InsertPeople(ret));
    }

    //得到选择后的下拉菜单规格表格
    private void getChance(String select) {
        //handlePublic.startLoad(startWork.this);
        new Thread(() -> {
            List<String> list = new ArrayList<>();
            list = net_startWork.SW_CommonMethod(Action.action.getSelect, select);
            handlePublic.setmHandler(SS, list);
        }).start();
    }

    //初始化下拉框
    private void setSpinner(String para) {
        Spinner spinner = findViewById(R.id.sp_dropdown);
        List<String> datalist = new ArrayList<>();
        if (para.indexOf("[") != -1) {
            try {
                jsonArray1 = new JSONArray(para);
                for (int i = 0; i < jsonArray1.length(); i++) {
                    datalist.add(jsonArray1.getJSONObject(i).get("cOperationName").toString());
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        } else {
            datalist.add(para);
        }
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, datalist);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

    /**
     * 扫描结果处理
     *
     * @param data
     */
    private void DataResult(String data) {
        View view = getCurrentFocus();
        handlePublic.getT(view, startWork.this);
        boolean Act = isFinishing();
        if (Act) {
            return;
        }
        switch (data.substring(0, 2)) {
            case "WO"://流传单结果
                EditText editText = findViewById(R.id.SQ);
                editText.setText(data);
                //handlePublic.startLoad(startWork.this);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getBarcode(data);
                    }
                }).start();
                break;
            case "EQ"://设备结果
            case "EM"://操作员结果
                getEMPQ(data);
                break;
            case "CQ"://标签结果
                if (jsonArray2 == null) {
                    handlePublic.Alert("请先扫描流传单", this);
                } else {
                    //handlePublic.startLoad(startWork.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                getCQTag(data);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }).start();
                }
                break;
            case "ED":
                getED(data);
                break;
        }
    }

    //得到数据库回调
    private void getData(int what, Object t) throws JSONException {
        EditText editText1 = findViewById(R.id.PC);
        EditText editText = findViewById(R.id.EQNum);
        //EditText editText2 = findViewById(R.id.people);
        Gson gson = new Gson();
        List listgetData;
        listgetData = (List) t;
        String getlist = listgetData.get(0).toString();
        if (getlist.indexOf("[") != -1 || getlist.indexOf("{") != -1) {
            switch (what) {
                case SW://流传单
                    jsonArray = new JSONArray(getlist);
                    editText1.setText(jsonArray.getJSONObject(0).get("cMOLotNo").toString());
                   // handlePublic.startLoad(startWork.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                getcMOLotNo(jsonArray.getJSONObject(0).get("cMOLotNo").toString());
                                //getProcss(jsonArray.getJSONObject(0).get("cMOLotNo").toString());
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }).start();
                    break;
                case GM:
                    jsonArray3 = new JSONArray(getlist);
                    isSelect = true;
                    //handlePublic.startLoad(startWork.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                getProcss(jsonArray.getJSONObject(0).get("cMOLotNo").toString());
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }).start();
                    break;
                case GP:
                    setSpinner(getlist);
                    isSelect = true;
                    break;
                case EQ://设备
                    EQ eq = gson.fromJson(getlist, com.example.beryl.entity.UserData.EQ.class);
                    editText.setText(eq.cSuperviseNo);
                    break;
                case EM://操作员
                    selectPM(getlist);
                    break;
                case SS:
                case GC:
                    jsonArray2 = new JSONArray(getlist);
                    setListView(jsonArray2);
                    break;
                case SBG://提交返回
                    if (getlist.equals("[0]")) {
                        //清空表单
                        cleanFrom();
                        handlePublic.Alert("提交成功", this);
                    }
                    break;
            }
        } else {
            if (getlist.contains("查询工序列表失败")) {
                list.clear();
                listView.setAdapter(null);
                setadapter();
                //Toast.makeText(startWork.this, getlist, Toast.LENGTH_SHORT).show();
            } else {
                handlePublic.Alert(getlist, this);
            }
        }
    }

    //获取裁切标签
    private void getCQTag(String data) throws JSONException {
        List<String> list1 = new ArrayList<>();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("table",jsonArray2.toString());
        jsonObject.put("da",data.split("-")[1]);
        //jsonArray2.put(data.split("-")[1]);
        System.out.println(jsonObject.toString());
        list1 = net_startWork.SW_CommonMethod(Action.action.getCQTag, jsonObject.toString());
        handlePublic.setmHandler(GC, list1);
    }

    //得到流传单信息
    private void getBarcode(String data) {
        List<String> list1 = new ArrayList<>();
        list1 = net_startWork.SW_CommonMethod(Action.action.GetBarcode, data);
        handlePublic.setmHandler(SW, list1);
    }

    //得到工序列表
    private void getProcss(String data) {
        List<String> list1;
        list1 = net_startWork.SW_CommonMethod(Action.action.getProce, data);
        handlePublic.setmHandler(GP, list1);
    }

    //获取设备或人员
    private void getEMPQ(String data) {
        String T = data.split("-")[0];
        Net_userData userData = new Net_userData();
        if (T.equals("EQ")) {
            AlertDialog.Builder builder = new AlertDialog.Builder(startWork.this);
            builder.setTitle("提示");
            builder.setMessage("确认好当前选择工序是否正确?");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("设备", data);
                    hashMap.put("参数", pro);
                    String json = handlePublic.MakeJson(hashMap);
                    //handlePublic.startLoad(startWork.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            List<String> list = new ArrayList<>();
                            list = userData.User_CommonMethod(Action.action.GetEM, json);
                            handlePublic.setmHandler(EQ, list);
                        }
                    }).start();
                }
            });
            builder.setNegativeButton("否",
                    (dialog, which) -> dialog.dismiss());
            if (!isFinishing()) {
                builder.create().show();
            }

        } else {
            //handlePublic.startLoad(startWork.this);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<String> list = new ArrayList<>();
                    list = userData.User_CommonMethod(Action.action.GetPerson, data.split("-")[1]);
                    handlePublic.setmHandler(EM, list);
                }
            }).start();
        }
    }

    //得到自定义二维码扫描结果
    private void getED(String data) {
        String[] res = data.split("-");
        if (list.isEmpty()) {
            HashMap<String, String> tempHash = new HashMap<String, String>();
            tempHash.put("项目", "项目");
            tempHash.put("材料批号", "材料批号");
            tempHash.put("类型", "类型");
            list.add(tempHash);
        }
        HashMap<String, String> tempHash1 = new HashMap<String, String>();
        tempHash1.put("项目", res[1]);
        tempHash1.put("材料批号", res[0]);
        tempHash1.put("类型", res[2]);
        list.add(tempHash1);
        setadapter();
    }

    //得到批次号信息
    private void getcMOLotNo(String cMOLotNo) {
        List<String> list1;
        list1 = net_startWork.SW_CommonMethod(Action.action.getMOLotNo, cMOLotNo);
        handlePublic.setmHandler(GM, list1);
    }

    //得到下拉菜单图标
    private void setListView(JSONArray jsonArray) throws JSONException {
        listView.setVisibility(View.VISIBLE);
        if (!list.isEmpty()) {
            list.clear();
        }
        getAllInfo(jsonArray);
        setadapter();
    }

    private void getDialogMessage(int i) {
        unregisterReceiver(mBroadcastReceiver);//弹出窗口时先注销监听
        final Dialog dialog = new Dialog(startWork.this);
        dialog.setContentView(R.layout.activity_update_data);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(false);//点击空白不消失
        dialog.setCancelable(false);//返回键不消失
        dialogWindow.setAttributes(lp);
        dialog.show();
        final EditText editText = dialog.findViewById(R.id.editText1);
        final Button button = dialog.findViewById(R.id.cancel_button);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i0, int i1, int i2) {
                dialog.dismiss();
                String res = charSequence.toString();
                UpdateInputvalue(res, i);
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        //点击取消后重新注册
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onResume();
                dialog.dismiss();
            }
        });
    }

    //更新数据列表inputvalue值
    private void UpdateInputvalue(String res, int i) {
        list.get(i).replace("材料批号", res);
        listView.setAdapter(null);
        setadapter();
        onResume();//重新监听广播
    }

    private void setadapter() {
        adapter1 = new SimpleAdapter(
                startWork.this,
                list,
                R.layout.activity_main4,
                new String[]{"项目", "材料批号", "类型"},
                new int[]{R.id.InspectionItem, R.id.inputvalue, R.id.parameter});
        listView.setAdapter(adapter1);
    }

    //已切信息处理，填充表格数据
    private List<HashMap<String, String>> getAllInfo(JSONArray jsonArray) throws JSONException {
        HashMap<String, String> tempHash = new HashMap<String, String>();
        tempHash.put("项目", "项目");
        tempHash.put("材料批号", "材料批号");
        tempHash.put("类型", "类型");
        list.add(tempHash);
        for (int j = 0; j < jsonArray.length(); j++) {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("项目", jsonArray.getJSONObject(j).get("InspectionItem").toString());
            hashMap.put("材料批号", jsonArray.getJSONObject(j).get("inputvalue").toString());
            hashMap.put("类型", jsonArray.getJSONObject(j).get("parameter").toString());
            list.add(hashMap);
        }
        return list;
    }

    private void checkData() throws JSONException {
        EditText editText2 = findViewById(R.id.EQNum);
        String txt = editText2.getText().toString();
        if (txt.equals(""))
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(startWork.this);
            builder.setTitle("提示");
            builder.setMessage("设备信息未被填写,是否继续？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    try {
                        summitData();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            builder.setNegativeButton("否",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            if (!isFinishing()) {
                builder.create().show();
            }
        }
        else
        {
            summitData();
        }
    }

    //选择操作员
    private void  selectPM(String ret) throws JSONException {
        String rets = "";
        rets = handlePublic.JosnChange(ret);
        JSONArray jsonret = new JSONArray(rets);
        //如果返回数据大于1
        if (jsonret.length() > 1)
        {
            handlePublic.AlterDialog(startWork.this,jsonret);
        }
        else
        {
            //返回一条数据时
            InsertPeople(ret);
        }
    }

    //更新操作员
    private void InsertPeople(String para)
    {
        Gson gson = new Gson();
        Person EM = gson.fromJson(para, Person.class);
        Action.person = EM;
        EditText editText2 = findViewById(R.id.people);
        editText2.setText(EM.cPsn_Name);
    }

    //数据提交
    private void summitData() throws JSONException {
        List<HashMap<String, String>> hashMapList = new ArrayList<>();
        HashMap<String, String> hashMap = new HashMap<>();
        EditText editText = findViewById(R.id.PC);
        EditText editText1 = findViewById(R.id.people);
        EditText editText2 = findViewById(R.id.EQNum);
        if (list.isEmpty()) {
            HashMap<String, String> h = new HashMap<>();
            h.put("项目", "1");
            list.add(h);
        } else {
            list.remove(0);//移除首行标题
        }
        hashMap.put("cMOLotNo", editText.getText().toString());
        hashMap.put("Operator", Action.person.cPsn_Num);
        hashMap.put("PEquipment", editText2.getText().toString());
        hashMap.put("IMaterialsNum", jsonArray3.getJSONObject(0).get("dLotQty").toString());//订单数量
        hashMap.put("cmaterialno", jsonArray3.getJSONObject(0).get("cMatNo").toString());//物料编码
        hashMap.put("specification", jsonArray.getJSONObject(0).get("cSpecifucation").toString());//物料规格
        hashMap.put("cProcess", pro);
        //hashMap.put("cProcessCode",Action.loginUser.cOperationNo);
        hashMapList = list;
        hashMapList.add(hashMap);
        Gson gson = new Gson();
        String josn = gson.toJson(hashMapList);
        System.out.println(josn);
        //handlePublic.startLoad(startWork.this);
            new Thread(() -> {
                List<String> list1 = new ArrayList<>();
                list1 = net_startWork.SW_CommonMethod(Action.action.summitBG, josn);
                handlePublic.setmHandler(SBG,list1);
            }).start();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        //MenuItem menuItem = menu.findItem(R.id.toolbar_user);
        //menuItem.setVisible(false);
        setVisible(true);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (mReceiverTag) {
            unregisterReceiver(mBroadcastReceiver);
            finish();
        }
    }

    /**
     * 清空表格
     */
    private void cleanFrom() {
        EditText editText1 = findViewById(R.id.PC);
        EditText editText = findViewById(R.id.EQNum);
        EditText editText2 = findViewById(R.id.people);
        isSelect = false;
        editText.setText("");
        editText1.setText("");
        editText2.setText("");
        list.clear();
        listView.setAdapter(null);
        setadapter();
        jsonArray = null;
        jsonArray1 = null;
        jsonArray2 = null;
        jsonArray3 = null;
        setadapter();
    }
}